home *** CD-ROM | disk | FTP | other *** search
/ OpenGL Superbible (2nd Edition) / OpenGL SuperBible e2.iso / tools / GLUT-3.7 / PROGS / CONTRIB / ENGINE.C < prev    next >
Encoding:
C/C++ Source or Header  |  1998-08-12  |  1.3 KB  |  76 lines

  1.  
  2. /* hanoi solver for hanoi2 */
  3.  
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <assert.h>
  7. #include <unistd.h>
  8.  
  9. static int num_disks[3] =
  10. {0, 0, 0};
  11.  
  12. static void
  13. move_disk(int from, int to, int fd)
  14. {
  15.   char buf[3];
  16.  
  17.   assert(from != to);
  18.   num_disks[from]--;
  19.   num_disks[to]++;
  20. #ifdef TEST_ENGINE
  21.   printf("%d --> %d\n", from, to);
  22. #else
  23.   buf[0] = 'M';
  24.   buf[1] = (char) from;
  25.   buf[2] = (char) to;
  26.   if (3 != write(fd, buf, 3)) {
  27.     perror("can't write");
  28.     exit(1);
  29.   }
  30. #endif
  31. }
  32.  
  33. static void
  34. move_disks(int from, int to, int n, int fd)
  35. {
  36.   static int other_table[9] =
  37.   {-1, 2, 1, 2, -1, 0, 1, 0, -1};
  38.   int other;
  39.  
  40.   assert(from != to);
  41.   other = other_table[from * 3 + to];
  42.   assert(other != -1);
  43.   if (n == 1) {
  44.     move_disk(from, to, fd);
  45.   } else {
  46.     move_disks(from, other, n - 1, fd);
  47.     move_disk(from, to, fd);
  48.     move_disks(other, to, n - 1, fd);
  49.   }
  50. }
  51.  
  52. void
  53. engine(int *args)
  54. {
  55.   num_disks[0] = args[0];
  56.   for (;;) {
  57.     move_disks(0, 2, args[0], args[1]);
  58.     move_disks(2, 0, args[0], args[1]);
  59.   }
  60. }
  61.  
  62. #ifdef TEST_ENGINE
  63. int
  64. main(int argc, char *argv[])
  65. {
  66.   int engine_args[2];
  67.  
  68.   if (argc > 1) {
  69.     engine_args[0] = atoi(argv[1]);
  70.   }
  71.   engine_args[1] = 1;
  72.   engine(n, engine_args);
  73.   return 0;             /* ANSI C requires main to return int. */
  74. }
  75. #endif
  76.